package zouhaotian.rbac.service.impl;

import zouhaotian.rbac.dao.IBaseDao;
import zouhaotian.rbac.domain.dto.BaseDto;
import zouhaotian.rbac.domain.entity.BaseEntity;
import zouhaotian.rbac.domain.vo.Basevo;
import zouhaotian.rbac.domain.vo.Result;
import zouhaotian.rbac.service.IBaseService;

import java.util.*;

/**
 * 业务层-基于容器存储数据
 *
 * @auther 邹昊天
 * @since 2025/6/21 14:12
 */
public abstract class BaseService<
        Entity extends BaseEntity,
        Dto extends BaseDto,
        Vo extends Basevo,
        Dao extends IBaseDao<Entity>> implements IBaseService<Entity,Dto> {

    Dao dao;


    Vo[] temp;


    Map<Integer, Entity> cache = new HashMap<>();
abstract Vo convertToVo(Entity entity);

void init(){
    dao.list().forEach(entity -> cache.put(entity.getId(), entity));
}

    @Override
    public Result list() {
       List<Vo> list = cache.values().stream().map(this::convertToVo).toList();

        return Result.success("查询成功",list.toArray(temp));

    }

    abstract Entity createEntity(Dto dto);

    @Override
    public Result create(Dto dto) {

        Entity entity = createEntity(dto);
        entity = dao.save(entity);
        cache.put(entity.getId(), entity);
        return Result.success("创建成功", null);
    }

    abstract void updateEntity(Dto dto, Entity entity);
    @Override
    public Result update(Dto dto, int id) {
        if (!existsById(id)){
            return Result.failure("更新失败，不存在该数据");
        }
        Entity entity= findById(id);
        updateEntity(dto, entity);
        entity = dao.save(entity);
        cache.put(entity.getId(), entity);
        return Result.success("更新成功", null);
    }

    @Override
    public boolean existsById(int id) {
        return cache.containsKey(id);
    }

    @Override
    public Entity findById(int id) {
        return cache.get(id);
    }
}
